<template>
  <view class="today-order-container">
    <status-bar bgColor="#0088ff"></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">{{pageTitle}}</view>
    </view>
    
    <!-- 日历选择区域 -->
    <view class="calendar-section">
      <view class="month-display">{{currentMonth}}</view>
      
      <!-- 周视图 - 水平滚动的日期选择器 -->
      <scroll-view v-if="!isMonthView" scroll-x class="date-scroll" :scroll-into-view="'date-'+selectedDate" show-scrollbar="false">
        <view class="date-list">
          <view 
            class="date-item" 
            :class="{ active: date.value === selectedDate }" 
            v-for="(date, index) in dateList" 
            :key="index"
            :id="'date-'+date.value"
            @click="selectDate(date.value)"
          >
            <text class="day-name">{{date.dayName}}</text>
            <text class="day-number">{{date.day}}</text>
            <text class="day-label">{{date.label}}</text>
          </view>
        </view>
      </scroll-view>
      
      <!-- 月视图 - 表格式日历 -->
      <view v-else class="calendar-grid">
        <!-- 星期标题行 -->
        <view class="week-header">
          <view class="week-day" v-for="(day, index) in ['日', '一', '二', '三', '四', '五', '六']" :key="index">
            {{day}}
          </view>
        </view>
        
        <!-- 日期网格 -->
        <view class="days-grid">
          <view 
            class="grid-item" 
            v-for="(date, index) in dateList" 
            :key="index"
            :class="{ 
              'active': date.value === selectedDate,
              'today': date.isToday,
              'other-month': !date.isCurrentMonth
            }"
            @click="selectDate(date.value)"
          >
            <text class="grid-day-number">{{date.day}}</text>
            <text v-if="date.isCurrentMonth" class="grid-day-label">{{date.label}}</text>
          </view>
        </view>
      </view>
      
      <view class="calendar-actions">
        <view class="calendar-action" @click="showMonthPicker" v-if="!isMonthView">
          <text>点击查看整月</text>
          <text class="arrow-down">▼</text>
        </view>
        <view class="calendar-action" @click="showWeekView" v-else>
          <text>返回本周视图</text>
          <text class="arrow-up">▲</text>
        </view>
      </view>
    </view>
    
      <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list">
      <block v-for="(order, index) in orderList" :key="index">
        <!-- 订单项 -->
        <view class="order-item">
          <!-- 预约时间 -->
          <view class="appointment-time">
            <text>预约时间：</text>
            <text class="time-value">{{order.appointmentTime}}</text>
          </view>
          
          <!-- 订单编号和标签 -->
          <view class="order-header">
            <view class="order-no-container">
              <text class="order-no">订单编号：{{order.orderNo}}</text>
              <view v-if="order.tag" class="order-tag" :class="getTagClass(order.tag)">
                <text class="tag-icon">!</text>
                {{order.tag}}
              </view>
            </view>
          </view>
          
          <!-- 客户信息和服务类型 -->
          <view class="customer-info">
            <view class="customer-left">
              <view class="location-icon">
                <image src="/static/images/icon/location.png" class="icon-img"></image>
              </view>
              <view class="customer-details">
                <view class="customer-name">{{order.customerName}}</view>
                <view class="service-type-tag" :class="getServiceTypeClass(order.orderType)">{{order.orderType == '1'? '窗帘测量': '窗帘安装'}}</view>
              </view>
            </view>
            <view class="service-status">
              <text>{{getOrderStatusText(order.orderStatus)}}</text>
              <text class="price">￥{{order.masterOrderFee}}</text>
            </view>
          </view>
          
          <!-- 地址 -->
          <view class="order-address">
            <text class="address-text">{{order.address}}</text>
          </view>
          
          <!-- 查看详情按钮 -->
          <view class="order-footer">
            <button class="detail-btn" @click="viewOrderDetail(order)">查看详情</button>
          </view>
        </view>
      </block>
      
      <!-- 加载中提示 -->
      <view class="loading-tip" v-if="loading">
        <uni-load-more status="loading" :contentText="{ contentdown: '加载中...', contentrefresh: '加载中...', contentnomore: '没有更多数据了' }"></uni-load-more>
      </view>
      
      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="!loading && noData">
        <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
        <text>当前日期暂无订单</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { ordeList } from '@/api/app/master/order.js'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue'

export default {
  components: {
    uniLoadMore
  },
  data() {
    // 获取当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = now.getDate();
    const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    
    return {
      currentMonth: `${year}年${month}月`, // 当前年月
      selectedDate: formattedDate, // 选中的日期（默认为今天）
      dateList: [], // 日期列表（将在onLoad中生成）
      isMonthView: false, // 是否显示整月视图
      orderList: [],
      loading: false,
      noData: false,
      pageTitle: '今日订单' // 默认页面标题
    }
  },
  onLoad(options) {
    // 初始化日期数据
    this.generateWeekDays()
    
    // 判断是否是查看明日订单
    if (options && options.type === 'tomorrow') {
      // 获取明日日期
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      const year = tomorrow.getFullYear();
      const month = tomorrow.getMonth() + 1;
      const day = tomorrow.getDate();
      const tomorrowDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
      
      // 更新页面标题
      this.pageTitle = '明日订单';
      uni.setNavigationBarTitle({
        title: '明日订单'
      });
      
      // 更新选中日期并加载数据
      this.selectedDate = tomorrowDate;
      
      // 在日期列表中找到明天的日期并设为选中状态
      for (let i = 0; i < this.dateList.length; i++) {
        if (this.dateList[i].value === tomorrowDate) {
          this.dateList[i].active = true;
          break;
        }
      }
    }
    
    // 加载初始订单数据
    this.loadOrdersByDate(this.selectedDate)
  },
  methods: {
    // 生成本周的日期数据
    generateWeekDays() {
      const today = new Date();
      const dayOfWeek = today.getDay(); // 0是周日，1是周一，以此类推
      
      // 计算本周的起始日期（周日）
      const startDate = new Date(today);
      startDate.setDate(today.getDate() - dayOfWeek);
      
      const weekDays = [];
      const dayNames = ['日', '一', '二', '三', '四', '五', '六'];
      
      // 生成本周7天的日期数据
      for (let i = 0; i < 7; i++) {
        const currentDate = new Date(startDate);
        currentDate.setDate(startDate.getDate() + i);
        
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1;
        const day = currentDate.getDate();
        
        // 格式化日期值
        const dateValue = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
        
        // 简单模拟农历日期（实际项目中可以使用专门的农历转换库）
        const lunarLabels = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
                           '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                           '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
        const lunarDay = (day + 10) % 30; // 简单模拟，实际应使用专业农历库
        const lunarLabel = lunarLabels[lunarDay];
        
        weekDays.push({
          value: dateValue,
          day: day.toString(),
          dayName: dayNames[i],
          label: lunarLabel
        });
        
        // 如果是今天，则设为选中状态
        if (currentDate.toDateString() === today.toDateString()) {
          this.selectedDate = dateValue;
        }
      }
      
      this.dateList = weekDays;
      this.isMonthView = false;
    },
    
    // 生成本月完整日历数据
    generateMonthDays() {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      
      // 更新当前月份显示
      this.currentMonth = `${year}年${month + 1}月`;
      
      // 获取本月第一天
      const firstDay = new Date(year, month, 1);
      // 获取本月最后一天
      const lastDay = new Date(year, month + 1, 0);
      // 本月总天数
      const totalDays = lastDay.getDate();
      
      // 获取本月第一天是星期几（0是周日，1是周一，以此类推）
      const firstDayOfWeek = firstDay.getDay();
      
      // 获取上个月的最后几天（用于填充本月日历的前几格）
      const prevMonth = month === 0 ? 11 : month - 1;
      const prevYear = month === 0 ? year - 1 : year;
      const prevMonthLastDay = new Date(prevYear, prevMonth + 1, 0).getDate();
      
      const calendarDays = [];
      const dayNames = ['日', '一', '二', '三', '四', '五', '六'];
      
      // 添加上个月的最后几天
      for (let i = 0; i < firstDayOfWeek; i++) {
        const day = prevMonthLastDay - firstDayOfWeek + i + 1;
        const dateValue = `${prevYear}-${(prevMonth + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
        
        calendarDays.push({
          value: dateValue,
          day: day.toString(),
          dayName: dayNames[i],
          label: '',
          isCurrentMonth: false
        });
      }
      
      // 添加本月的天数
      for (let i = 1; i <= totalDays; i++) {
        const currentDate = new Date(year, month, i);
        const dayOfWeek = currentDate.getDay();
        
        // 格式化日期值
        const dateValue = `${year}-${(month + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
        
        // 简单模拟农历日期
        const lunarLabels = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
                           '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                           '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
        const lunarDay = (i + 10) % 30; // 简单模拟，实际应使用专业农历库
        const lunarLabel = lunarLabels[lunarDay];
        
        // 检查是否是今天
        const isToday = currentDate.toDateString() === new Date().toDateString();
        
        calendarDays.push({
          value: dateValue,
          day: i.toString(),
          dayName: dayNames[dayOfWeek],
          label: lunarLabel,
          isCurrentMonth: true,
          isToday: isToday
        });
      }
      
      // 添加下个月的前几天（填充剩余的格子，使总数为7的倍数）
      const remainingDays = 42 - calendarDays.length; // 6行7列 = 42格
      const nextMonth = month === 11 ? 0 : month + 1;
      const nextYear = month === 11 ? year + 1 : year;
      
      for (let i = 1; i <= remainingDays; i++) {
        const dateValue = `${nextYear}-${(nextMonth + 1).toString().padStart(2, '0')}-${i.toString().padStart(2, '0')}`;
        
        calendarDays.push({
          value: dateValue,
          day: i.toString(),
          dayName: dayNames[(firstDayOfWeek + totalDays + i - 1) % 7],
          label: '',
          isCurrentMonth: false
        });
      }
      
      // 更新日期列表
      this.dateList = calendarDays;
      this.isMonthView = true;
      
      // 提示用户已切换到整月视图
      uni.showToast({
        title: '已切换到整月视图',
        icon: 'none'
      });
    },
    
    // 显示月份选择器，加载本月完整日历数据
    showMonthPicker() {
      // 生成本月完整日历数据
      this.generateMonthDays();
    },
    
    // 显示本周视图
    showWeekView() {
      // 生成本周日期数据
      this.generateWeekDays();
      
      // 提示用户已切换到本周视图
      uni.showToast({
        title: '已切换到本周视图',
        icon: 'none'
      });
    },
    
    goBack() {
      uni.navigateBack()
    },
    
    // 选择日期
    selectDate(date) {
      this.selectedDate = date
      // 这里应该调用接口获取选中日期的订单数据
      this.loadOrdersByDate(date)
    },
    
    // 获取标签样式类
    getTagClass(tag) {
      if (tag === '加急') {
        return 'urgent-tag'
      }
      return ''
    },
    
    // 获取服务类型样式类
    getServiceTypeClass(type) {
      if (type == '1') {
        return 'measure-tag'
      } else if (type == '2') {
        return 'install-tag'
      }
      return ''
    },
    
    // 查看订单详情
    viewOrderDetail(item) {
       const status = this.getOrderStatusText(item.orderStatus);
       console.log(status)
      // 如果订单状态是"待预约"，跳转到预约操作页面
      if (status === '待预约' || status === '异常订单') {
        uni.navigateTo({
          url: '/pages/order/order-appointment?id=' + item.id
        });
      } 
      // 如果订单状态是"待服务"，跳转到订单详情页面
      else if (status === '待服务' || status === '待验收' || status === '已完成' || status === '已售后')   {
        uni.navigateTo({
          url: '/pages/order/order-detail?id=' + item.id
        });
      }
      else {
        // 其他状态的订单暂时只显示提示
        uni.showToast({
          title: '查看订单: ' + id,
          icon: 'none'
        });
      }
      // 实际项目中应该跳转到订单详情页
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      /** 订单状态
      * 1：待派单；
      * 2：待预约；
      * 3：待服务；
      * 4：待验收；
      * 5：已完成；
      * 9：已售后；
      * 99：异常订单；
      */
      const statusMap = {
        '1': '待派单',
        '2': '待预约',
        '3': '待服务',
        '4': '待验收',
        '5': '已完成',
        '9': '已售后',
        '99': '异常订单'
      };
      return statusMap[status] || '待服务'; // 如果没有匹配的状态，默认显示"待服务"
    },
    
    // 姓名脱敏处理
    maskName(name) {
      if (!name) return '';
      if (name.length === 1) return name;
      if (name.length === 2) return name.substring(0, 1) + '*';
      return name.substring(0, 1) + '*'.repeat(name.length - 2) + name.substring(name.length - 1);
    },
    
    // 根据日期加载订单数据
    loadOrdersByDate(date) {
      this.loading = true;
      this.noData = false;
      
      // 构建请求参数
      const params = {
        reservationTime: date+" 00:00" // 传递选中的日期
      };
      
      // 调用接口获取订单数据
      ordeList(params).then(res => {
        if (res.code === 200) {
          // 获取数据成功
          const orders = res.rows || [];
          
          if (orders.length === 0) {
            this.noData = true;
          }
          
          // 处理返回的数据
          this.orderList = orders.map(item => {
            // 格式化预约时间为 yyyy-MM-dd HH:mm
            let formattedTime = '';
            if (item.reservationTime) {
              const dateTime = new Date(item.reservationTime);
              if (!isNaN(dateTime.getTime())) {
                const year = dateTime.getFullYear();
                const month = (dateTime.getMonth() + 1).toString().padStart(2, '0');
                const day = dateTime.getDate().toString().padStart(2, '0');
                const hours = dateTime.getHours().toString().padStart(2, '0');
                const minutes = dateTime.getMinutes().toString().padStart(2, '0');
                formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
              } else {
                formattedTime = item.reservationTime;
              }
            }
            
            return {
              id: item.id || '',
              appointmentTime: formattedTime,
              orderNo: item.orderNo || '',
              tag: item.urgent == 1 ? '加急' : '',
              customerName: item.ownerName ? this.maskName(item.ownerName) : '',
              customerAvatar: item.customerAvatar || '/static/images/profile.jpg',
              serviceType: item.measureDescribe || '',
              orderType: item.orderType || '1', // 添加订单类型，默认为1（窗帘测量）
              address: item.ownerProvincial+item.ownerCity+item.ownerCounty+item.ownerAddress || '',
              price: item.orderFee || '0.00',
              masterOrderFee: item.masterOrderFee || '0.00',
              orderStatus: item.orderStatus || '' // 添加订单状态，默认为3（待服务）
            };
          });
        } else {
          // 获取数据失败
          uni.showToast({
            title: res.msg || '获取订单数据失败',
            icon: 'none'
          });
          this.noData = true;
          this.orderList = [];
        }
      }).catch(err => {
        console.error('获取订单数据失败:', err);
        uni.showToast({
          title: '获取订单数据失败，请稍后重试',
          icon: 'none'
        });
        this.noData = true;
        this.orderList = [];
      }).finally(() => {
        this.loading = false;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.today-order-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #0088ff;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

/* 日历选择区域 */
.calendar-section {
  background-color: #0088ff;
  padding: 0 0 20rpx;
  color: #fff;
}

.month-display {
  text-align: center;
  font-size: 32rpx;
  padding: 10rpx 0;
}

/* 周视图样式 */
.date-scroll {
  white-space: nowrap;
  padding: 20rpx 0;
}

.date-list {
  display: flex;
  padding: 0 20rpx;
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 20rpx;
  padding: 10rpx 0;
  width: 80rpx;
}

.date-item.active {
  background-color: #fff;
  border-radius: 10rpx;
  color: #0088ff;
}

.day-name {
  font-size: 24rpx;
  margin-bottom: 10rpx;
}

.day-number {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.day-label {
  font-size: 22rpx;
}

/* 月视图样式 */
.calendar-grid {
  padding: 10rpx 20rpx;
}

.week-header {
  display: flex;
  justify-content: space-between;
  padding: 10rpx 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.week-day {
  width: 14.28%;
  text-align: center;
  font-size: 28rpx;
}

.days-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx 0;
}

.grid-item {
  width: 14.28%;
  height: 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 5rpx 0;
  position: relative;
}

.grid-item.active {
  background-color: #fff;
  border-radius: 10rpx;
  color: #0088ff;
}

.grid-item.today {
  font-weight: bold;
}

.grid-item.other-month {
  opacity: 0.5;
}

.grid-day-number {
  font-size: 28rpx;
}

.grid-day-label {
  font-size: 20rpx;
  margin-top: 4rpx;
}

.calendar-actions {
  display: flex;
  justify-content: center;
}

.calendar-action {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.arrow-down {
  font-size: 20rpx;
  margin-left: 10rpx;
}

.arrow-up {
  font-size: 20rpx;
  margin-left: 10rpx;
}

/* 订单列表 */
.order-list {
  height: calc(100vh - 300rpx);
  padding: 0;
  background-color: #f5f5f5;
}

.order-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx;
  position: relative;
}

/* 预约时间 */
.appointment-time {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.time-value {
  color: #ff8c00;
  font-size: 32rpx;
  font-weight: bold;
}

/* 订单编号和标签 */
.order-header {
  margin-bottom: 20rpx;
}

.order-no-container {
  display: flex;
  align-items: center;
}

.order-no {
  font-size: 28rpx;
  color: #333;
}

.order-tag {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  margin-left: 10rpx;
  color: #fff;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.tag-icon {
  display: inline-block;
  width: 20rpx;
  height: 20rpx;
  line-height: 20rpx;
  text-align: center;
  border-radius: 50%;
  background-color: #fff;
  color: #ff3b30;
  font-weight: bold;
  margin-right: 4rpx;
  font-size: 20rpx;
}

.urgent-tag {
  background-color: #ff3b30;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 客户信息和服务类型 */
.customer-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.customer-left {
  display: flex;
  align-items: center;
}

.location-icon {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10rpx;
}

.icon-img {
  width: 40rpx;
  height: 40rpx;
}

.customer-details {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.customer-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 15rpx;
}

.service-type-tag {
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 30rpx; /* 使用更大的圆角实现胶囊形状 */
  color: #fff;
  display: inline-block;
  line-height: 1.5;
}

.measure-tag {
  background-color: #4cd964;
}

.install-tag {
  background-color: #007aff;
}

.service-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  color: #ff8c00;
}

.price {
  font-size: 36rpx;
  font-weight: bold;
  margin-top: 5rpx;
}

/* 地址 */
.order-address {
  margin-bottom: 20rpx;
  padding-left: 60rpx;
}

.address-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}

/* 查看详情按钮 */
.order-footer {
  display: flex;
  justify-content: flex-end;
}

.detail-btn {
  background-color: #fff;
  color: #0088ff;
  font-size: 28rpx;
  padding: 8rpx 30rpx;
  border-radius: 30rpx;
  border: 1px solid #0088ff;
  line-height: 1.5;
  margin: 0;
}

/* 无数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}
</style>